import com.Ostermiller.util.LabeledCSVParser
import com.Ostermiller.util.CSVParser

/**
 * Extends the Reader interface to iterate through a CSV DataReader
 * - uses the OsterMiller CSV Reader
 *
 * This file implements a generic CSV File reader that reads columns from a CSV file 
 * and returns the whole thing as an array of ordered Hashtables for each row
 */
class CSVDataReader extends RowDataReader
{
    Logger logger = Logger.getLogger()
    LabeledCSVParser lcsvp
    RowDataSource dataSource

    /**
     * overridden reader.init() method to create CSV readers
     */
    CSVDataReader(RowDataSource dataSource)
    {
        super.init(dataSource)

        // first read the whole thing into a text string
        String text = ""

        text = Utils.readFileLocalOrRemote(dataSource.name)

        // now do the factory thing of creating a CSV Reader
        CSVParser csvParser = new CSVParser(new StringReader(text))
        LabeledCSVParser lcsvp = new LabeledCSVParser(csvParser);
        this.lcsvp = lcsvp
    }

    // overridden reader.getValue() to provide CSV implementation
    String getFieldValue(String fieldName)
    {
        return Utils.readTrimmedStr(lcsvp.getValueByLabel(fieldName))
    }
    
    // String[]
    def getFieldNames()
    {
        return lcsvp.getLabels()
    }

    // overridden reader.iterate() to provide CSV data source iteration
    void iterate(rowCallbackClosure)
    {
        while(lcsvp.getLine()!=null)
        {
            //this.rowIterCallback(rowNum)
            rowCallbackClosure(lcsvp)
        }
    }

    static void main(args)
    {
        RowDataSource   dataSource = new RowDataSource("./inputdata/subprocesstimeline.csv", "CSV")
        CSVDataReader   dataReader = new CSVDataReader(dataSource)

        println dataReader
        println dataReader.getFieldNames()

        def rowCallbackClosure = { row -> 
            println row.lastLineNumber() + ". "+ Utils.readTrimmedStr(row.getValueByLabel("Business Process"))
        }

        dataReader.iterate(rowCallbackClosure)
    }
}
